use super::*;

pub const VALUE_COUNT: u16 = 32;

#[derive(Debug, Clone)]
pub struct Table<'a> {
	// fixed32	version	Version number of the Baseline table (0x00010000 for the current version).
	pub version: i32,
	// uint16	format	Format of the baseline table. Only one baseline format may be selected for the font.
	// 0	Distance-based, no mapping.
	// 1	Distance-based, with mapping.
	// 2	Control point-based, no mapping.
	// 3	Control point-based, with mapping.
	pub format: u16,
	// uint16	defaultBaseline	Default baseline value for all glyphs. This value can be from 0 through 31.
	pub default_baseline: u16,
	// variable	parts	Format-specific data. This will be either a Format0Part, a Format1Part, a Format2Part or a Format3Part, depending on the value of the format field.
	pub parts: Parts<'a>,
}
impl<'a> Table<'a> {
	pub const ROMAN: u16 = 0;
	pub const IDEOGRAPHIC_CENTERED: u16 = 0;
	pub const IDEOGRAPHIC_LOW: u16 = 0;
	pub const HANGING: u16 = 0;
	pub const MATH: u16 = 0;

	pub fn parse(num_glyphs: u16, data: &'a [u8]) -> Option<Self> {
		let mut s = Stream::new(data);
		let version: i32 = s.read()?;
		let format: u16 = s.read()?;
		Some(Self {
			version,
			format,
			default_baseline: s.read()?,
			parts: match format {
				0 => Parts::Format0 {
					deltas: s.read_array16(VALUE_COUNT)?,
				},
				1 => Parts::Format1 {
					deltas: s.read_array16(VALUE_COUNT)?,
					mapping_data: aat::Lookup::parse(num_glyphs, s.tail()?)?,
				},
				2 => Parts::Format2 {
					std_glyph: s.read()?,
					ctl_points: s.read_array16(VALUE_COUNT)?,
				},
				3 => Parts::Format3 {
					std_glyph: s.read()?,
					ctl_points: s.read_array16(VALUE_COUNT)?,
					mapping_data: aat::Lookup::parse(num_glyphs, s.tail()?)?,
				},
				_ => return None,
			},
		})
	}
}

#[derive(Debug, Clone)]
pub enum Parts<'a> {
	Format0 {
		deltas: LazyArray16<'a, i16>,
	},
	Format1 {
		deltas: LazyArray16<'a, i16>,
		mapping_data: aat::Lookup<'a>,
	},
	Format2 {
		std_glyph: GlyphId,
		ctl_points: LazyArray16<'a, u16>,
	},
	Format3 {
		std_glyph: GlyphId,
		ctl_points: LazyArray16<'a, u16>,
		mapping_data: aat::Lookup<'a>,
	},
}
